/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.minhphuong.controllers;

import com.minhphuong.bll.*;
import com.minhphuong.entities.*;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author QuocMinh
 */
@Controller

public class NguoiDungController {

    @RequestMapping(value = "/DangKi", method = RequestMethod.GET)
    public String DangKi(@ModelAttribute("nguoidung") NguoiDung nguoidung, ModelMap model, HttpSession session) {
        HelperBLL.LoadGiaoDien(model, session);
        String captcha = NguoiDungBLL.create_captcha(4);
        model.addAttribute("captcha", captcha);

        return "dangki";
    }

    @RequestMapping(value = "/DangKi/XuLi", method = RequestMethod.POST)
    public String XuLiDangKi(@ModelAttribute("nguoidung") NguoiDung nguoidung, HttpSession session, ModelMap model) {
        HelperBLL.LoadGiaoDien(model, session);
        nguoidung.setQuyen(QuyenBLL.getQuyenByID(4));
        NguoiDungBLL.insertNguoiDung(nguoidung);

        return "index";
    }

    @RequestMapping(value = "/DangNhap", method = RequestMethod.GET)
    public String DangNhap(@ModelAttribute("nguoidung") NguoiDung nguoidung, ModelMap model, HttpSession session) {
        HelperBLL.LoadGiaoDien(model, session);
        NguoiDung nguoiDung = (NguoiDung) session.getAttribute("nguoiDung");
        if (nguoiDung != null) {
            return "redirect:/";
        }
        return "dangnhap";
    }

    @RequestMapping(value = "/DangNhap/XuLi", method = RequestMethod.POST)
    public String XuLiDangNhap(@ModelAttribute("nguoidung") NguoiDung nguoidung, HttpSession session, ModelMap model) {

        HelperBLL.LoadGiaoDien(model, session);
        NguoiDung nguoiDung = NguoiDungBLL.checkLogin(nguoidung.getEmail(), nguoidung.getMatKhau());
        if (nguoiDung != null) {
            session.setAttribute("nguoiDung", nguoiDung);
            return "redirect:/";
        } else {
            return "redirect:/DangNhap?error=1";
        }
    }

    @RequestMapping(value = "/DangXuat", method = RequestMethod.GET)
    public String DangXuat(HttpSession session) {
        session.removeAttribute("nguoiDung");
        return "redirect:/";
    }
}
